import java.time.DayOfWeek
import java.time.LocalDate
import java.time.YearMonth
import java.time.temporal.WeekFields
import java.util.*

fun main() {
    val yearMoth = YearMonth.now()
    val year = yearMoth.year
    val month = yearMoth.monthValue

    val thisMonthDays = (1..yearMoth.lengthOfMonth()).map {
        LocalDate.of(year, month, it)
    }

    val firstDayOfWeek = daysOfWeekFromLocale().first() //星期一对应的DayOfWeek,也就是第一天
    println("firstDayOfWeek=${firstDayOfWeek}")
    val weekField = WeekFields.of(firstDayOfWeek, 1)
    println("weekField=${weekField}")
    val weekOfMonthField = weekField.weekOfMonth()
    println("weekOfMonthField=${weekOfMonthField}")
    val groupByWeekOfMonth = thisMonthDays.groupBy {
        var temp = it.get(weekOfMonthField) //获取第几周
        println("temp=${temp}")
        temp
    }.values.toMutableList()
    val firstWeek = groupByWeekOfMonth.first()
    println("firstWeek=${firstWeek}")
//    println("weekOfMonthField=${weekOfMonthField}\ngroupByWeekOfMonth=${groupByWeekOfMonth}")
}

fun daysOfWeekFromLocale(): Array<DayOfWeek> {
    val firstDayOfWeek = WeekFields.of(Locale.CHINA).firstDayOfWeek
    var daysOfWeek = DayOfWeek.values()
    // Order `daysOfWeek` array so that firstDayOfWeek is at index 0.
    // Only necessary if firstDayOfWeek != DayOfWeek.MONDAY which has ordinal 0.
    if (firstDayOfWeek != DayOfWeek.MONDAY) {
        val rhs = daysOfWeek.sliceArray(firstDayOfWeek.ordinal..daysOfWeek.indices.last)
        val lhs = daysOfWeek.sliceArray(0 until firstDayOfWeek.ordinal)
        daysOfWeek = lhs + rhs
    }
    return daysOfWeek
}